package org.bultreebank.search_engine.integration;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.bultreebank.extractor.Extractor;
import org.bultreebank.index.utils.Constants;
import org.bultreebank.searching.SearchImpl;
import org.w3c.dom.Document;

public class SearchEngineImpl extends org.bultreebank.search_engine.SearchEngineImpl implements SearchEngine, Constants
{
	private static SearchEngine engine;
	
	
	private SearchEngineImpl(String searchEnginePath) throws Exception
	{
		super(searchEnginePath);
	}
	@Override
	public Extractor getExtractor()
	{
		return extractor;
	}
	
	public synchronized void indexDocument(Document xmlDoc,
			Document metadataDoc,
			String indexID, String docID) throws Exception
	{
		indexManager.indexDocument(xmlDoc,metadataDoc,
				indexID, docID, false);
	
	}

	public synchronized void indexDocument(String docID, Document metadataDoc,
			String indexID) throws Exception
	{
		indexManager.indexDocument(docID,metadataDoc,
				indexID, false);
	}

	@Override
	public synchronized void removeDocument(String docID,
			String indexID)	throws Exception
	{
		indexManager.deleteDocFromIndex(docID, indexID);
		indexDocumentsManager.deleteDocumentForIndex(indexID, docID);
	}

	public static SearchEngine getInstance(String searchEnginePath) throws Exception {
		if (engine == null)
			engine = new SearchEngineImpl(searchEnginePath);
		return engine;
	}
	public synchronized void registerIndex(Document indexingSchemaDocument)
	throws Exception
	{
		indexSchemaManager.addIndexSchema(indexingSchemaDocument);
	}
	@Override
	public String[] search(Document queryDoc, String indexID) throws Exception {
		boolean isQueryValid = org.bultreebank.index.utils.Validator.isQueryValid(org.bultreebank.search_engine.SearchEngineImpl.repositoryPath, queryDoc);
		if (!isQueryValid)
			throw new Exception ("The query documents is NOT valid!");
		Map<String, Set<String>> result = ((SearchImpl) searchManager).search(queryDoc, 
				indexID);
		String[] resultDocs = new String[result.size()];
		Iterator<String> resultIter = result.keySet().iterator();
		int i = 0;
		while(resultIter.hasNext())
		{
			StringBuffer buf = new StringBuffer();
			String context = resultIter.next();
			Set<String> docIDs = result.get(context);
			Iterator<String> docIDsIter = docIDs.iterator();
			if (docIDsIter.hasNext())
				buf.append(context + SPEC_CHAR);
			while (docIDsIter.hasNext())
				buf.append(docIDsIter.next() + WHITESPACE);
			resultDocs[i] = buf.toString();
			i++;
		}
		return resultDocs;
	}
}
